// @Date         2021-11-18
// @Author       Aaron Zhang
// @Description
// @FileName      file-rotate.go

package log

import (
	"errors"
	"fmt"
	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"time"
	"zin/config"
)

func getRotateWriter(logFile string) (*rotatelogs.RotateLogs, error) {
	cfg := config.Conf.Log

	//切割选项
	option := make([]rotatelogs.Option, 0)

	//时间戳
	dataFormat := "%Y%m%d%h%m"
	if cfg.DateFormat != "" {
		dataFormat = cfg.DateFormat
	}

	option = append(option, rotatelogs.WithLinkName(logFile))

	//rotate_count 存储文件人数量，默认30天
	var rotateCount uint = 30
	if cfg.RotateCount > 0 {
		rotateCount = cfg.RotateCount
	}
	option = append(option, rotatelogs.WithRotationCount(rotateCount))

	//rotate_size 默认 约等于100M进行切割
	var rotateSize int64 = 100000000
	if cfg.RotateSize > 0 {
		rotateSize = cfg.RotateSize
	}
	option = append(option, rotatelogs.WithRotationSize(rotateSize))

	//rotate_time 尽量与 rotate_size 不要同时存在
	if cfg.RotateSize <= 0 && cfg.RotateTime != "" {
		RotateTime := "2m"
		if cfg.RotateTime != "" {
			RotateTime = cfg.RotateTime
		}
		rotateDuration, _ := time.ParseDuration(RotateTime)
		option = append(option, rotatelogs.WithRotationTime(rotateDuration))
	}

	//max_age 默认最多保存30天
	maxAge := "30d"
	if cfg.MaxAge != "" {
		maxAge = cfg.MaxAge
	}
	maxAgeDuration, _ := time.ParseDuration(maxAge)
	option = append(option, rotatelogs.WithMaxAge(maxAgeDuration))

	fd, err := rotatelogs.New(
		fmt.Sprintf("%s-%s", logFile, dataFormat),
		option...,
	)

	if err != nil {
		return nil, errors.New("open log file err")
	}
	return fd, nil
}
